

import axios from "axios";
import { getQueryVariable } from "@/utils/utils";
import { showToast  } from 'vant';

// console.log(window.location.pathname);  
// let currentPath = window.location.pathname

var baseURL = 'https://ya30api.hbwlife.com/wxmp';
const instance = axios.create({
  headers: {
    "Content-Type":"application/json;charset=utf8"
  },
  baseURL: baseURL,
  timeout: 3000000,
  withCredentials: false
});


function GetRequest() {
    var url = location.search; //获取url中"?"符后的字串
    var theRequest = new Object();
    if (url.indexOf("?") != -1) {
        var str = url.substr(1);
        let strs = str.split("&");
        for(var i = 0; i < strs.length; i ++) {
            theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
        }
    }
    return theRequest;
}

// 添加请求拦截器
instance.interceptors.request.use(
  config => {
    var user_id = localStorage.getItem("user_id");
    var access_token = localStorage.getItem("access_token");
    var open_id = localStorage.getItem("open_id");
    
    if (access_token) {
      config.headers["AUTH-TOKEN"] = user_id + "|" + access_token + "|" + open_id
    }
    return config;
  },
  error => {}
);

// 添加响应拦截器
instance.interceptors.response.use(
  response => {
    if (response.status === 200) {
      if (response.data && response.data.code == 0) {
        return response; 
      } else if (response.data && response.data.code == -56055) {
          showToast("登录已超时，即将重新登录");
          let href = window.location.href
          if(href.indexOf('?') !== -1) {
              href = href.split('?')[0]
          }
          var Request = GetRequest();
          let currentPath = Request['currentPath']
          setTimeout(() => {
              if(currentPath) {
                  wx && wx.miniProgram.navigateTo({
                      url: '/pages/loginToken/index?currentPath='+encodeURIComponent(currentPath),
                  })
              }

          }, 1000)

        //token失效
        // Toast("登录已超时，即将重新登录");
         /*wx && wx.navigateTo({
          url: '/pagesC/myInfo/myInfo',
        })*/

      
        // let currentPath = localStorage.getItem("currentPath")
        // let tokenStatus = false;
        // setTimeout(() => {
        //   uni.navigateTo({
        //     url: `/${currentPath}?tokenStatus=${tokenStatus}`,
        //   })
        // }, 2000);
        
       
        // // 首先，你可以在全局事件中发送参数
        //   uni.$on('setParam', (tokenStatus) => {
        //     // 可以在这里做一些处理，例如存储到某个全局变量中
        //     console.log('Received param:', tokenStatus);
        // });
        // // 触发设置参数的事件
        // uni.$emit('setParam', tokenStatus);
        // // 然后使用switchTab跳转到带有tabbar的页面
        // uni.switchTab({
        //     url: '/pages/home/index/index'
        //   })

        return response;
      } else if (response.data && response.data.code == -57029) {
        router.push("/noFollow")
      }
    }
    return response;
  },
  error => {
    return Promise.reject(error.response.data); 
  }
);



/**
 * get方法，对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function getData(url, data) {
  return new Promise((resolve, reject) => {
    instance
      .get(baseURL + url, {
        params: data
      })
      .then(res => {
        resolve(res.data);
      })
      .catch(err => {
        reject(err.data);
      });
  });
}

/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} data [请求时携带的参数]
 * @param {Object} config 配置参数
 */
export function postData(url, data, config = {}) {
  return new Promise((resolve, reject) => {
    //console.log(baseURL + url);
    instance
      .post(baseURL + url, data, config)
      .then(res => {
        // console.log(res.data);
        resolve(res.data);
      })
      .catch(err => {
        reject(err.data);
      });
  });
}



